package cn.lliiooll.ippzonetoolbox.ui.activities.nowm;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import cn.lliiooll.ippzonetoolbox.R;
import cn.lliiooll.ippzonetoolbox.task.PTaskBuilder;
import cn.lliiooll.ippzonetoolbox.ui.activities.input.InputActivity;
import cn.lliiooll.ippzonetoolbox.utils.ActivitiesManager;
import cn.lliiooll.ippzonetoolbox.utils.FileUtils;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import lombok.Getter;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URL;

@Route(path = "/ipp/nowm")
public class NowmActivity extends AppCompatActivity {
    @Getter
    public static NowmActivity instance;

    @Autowired(name = "url")
    public String url;

    private File file;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        ARouter.getInstance().inject(this);
        setContentView(R.layout.activity_nowm);
        ActivitiesManager.add(this);

        EditText editText = findViewById(R.id.nowm_2_edittext);
        editText.setText(url);
        final Button save = findViewById(R.id.nowm_2_button);
        save.setBackgroundResource(R.drawable.ic_button_24dp);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(InputActivity.getInstance(), "正在保存...", Toast.LENGTH_SHORT).show();
                save.setEnabled(false);
                NowmActivity.this.file = FileUtils.getFile(url);
                ActivityCompat.requestPermissions(NowmActivity.this,
                        new String[]{
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS
                        }, 1);
            }
        });
        VideoView videoView = findViewById(R.id.nowm_2_video);
        videoView.setVideoURI(Uri.parse(url));
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(final MediaPlayer mediaPlayer) {
                Button play = NowmActivity.this.findViewById(R.id.nowm_2_button_play);
                Button pause = NowmActivity.this.findViewById(R.id.nowm_2_button_pause);
                play.setBackgroundResource(R.drawable.ic_button_24dp);
                pause.setBackgroundResource(R.drawable.ic_button_24dp);
                play.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mediaPlayer.start();
                    }
                });
                pause.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mediaPlayer.pause();
                    }
                });
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //Toast.makeText(MainActivity.this, "Permission GET", Toast.LENGTH_SHORT).show();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {// 大于等于安卓10
                PTaskBuilder.builder().setLabel("io-1").setRunnable(new Runnable() {
                    @SneakyThrows
                    @Override
                    public void run() {
                        org.apache.commons.io.FileUtils.writeByteArrayToFile(NowmActivity.this.file, IOUtils.toByteArray(new URL(url).openConnection().getInputStream()));
                    }
                }).onFinished(new Runnable() {
                    @SneakyThrows
                    @Override
                    public void run() {
                        String fileName = NowmActivity.this.file.getName();
                        ContentValues values = new ContentValues();
                        values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
                        values.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4");
                        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/pipitoolbox");
                        ContentResolver contentResolver = NowmActivity.this.getContentResolver();
                        final Uri uri = contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
                        if (uri == null) {
                            NowmActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    new AlertDialog.Builder(NowmActivity.this)
                                            .setTitle("保存失败")
                                            .setMessage("保存失败")
                                            .setPositiveButton("确定", null)
                                            .show();
                                }
                            });
                        } else {
                            OutputStream out = contentResolver.openOutputStream(uri);
                            FileInputStream fis = new FileInputStream(file);
                            android.os.FileUtils.copy(fis, out);
                            fis.close();
                            out.close();
                            NowmActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    new AlertDialog.Builder(NowmActivity.this)
                                            .setTitle("保存完毕")
                                            .setMessage("文件名: " + NowmActivity.this.file.getName())
                                            .setPositiveButton("确定", null)
                                            .show();
                                    Button save = findViewById(R.id.nowm_2_button);
                                    save.setEnabled(true);
                                }
                            });
                        }
                    }
                }).start();
            } else {
                if (!file.canWrite()) {
                    new AlertDialog.Builder(this)
                            .setTitle("保存失败")
                            .setMessage("没有权限")
                            .setPositiveButton("确定", null)
                            .show();
                } else {
                    PTaskBuilder.builder().setLabel("io-0").setRunnable(new Runnable() {
                        @SneakyThrows
                        @Override
                        public void run() {
                            org.apache.commons.io.FileUtils.writeByteArrayToFile(NowmActivity.this.file, IOUtils.toByteArray(new URL(url).openConnection().getInputStream()));
                        }
                    }).onFinished(new Runnable() {
                        @Override
                        public void run() {
                            NowmActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    new AlertDialog.Builder(NowmActivity.this)
                                            .setTitle("保存完毕")
                                            .setMessage("路径: " + NowmActivity.this.file.getAbsolutePath())
                                            .setPositiveButton("确定", null)
                                            .show();
                                    Button save = findViewById(R.id.nowm_2_button);
                                    save.setEnabled(true);
                                }
                            });
                        }
                    }).start();
                    this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
                }
            }
//保存图片的方法，自定义
        } else {
//             Permission Denied
            //Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            new AlertDialog.Builder(this)
                    .setTitle("保存失败")
                    .setMessage("没有权限")
                    .setPositiveButton("确定", null)
                    .show();
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
